package org.dromara.system.service.impl;

import lombok.extern.slf4j.Slf4j;
import cn.hutool.core.collection.CollUtil;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.core.utils.MapstructUtils;
    import org.dromara.common.mybatis.core.page.TableDataInfo;
    import org.dromara.common.mybatis.core.page.PageQuery;
    import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.dromara.system.domain.bo.SysAccountBo;
import org.dromara.system.domain.vo.SysAccountVo;
import org.dromara.system.domain.SysAccount;
import org.dromara.system.mapper.SysAccountMapper;
import org.dromara.system.service.ISysAccountService;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import java.util.function.Function;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Collection;

/**
 * 账号Service业务层处理
 *
 * @author yilong.fu
 * @date 2024-09-14
 */
@RequiredArgsConstructor
@Service
@Slf4j
public class SysAccountServiceImpl implements ISysAccountService {

    private final SysAccountMapper baseMapper;

    /**
     * 查询账号
     */
    @Override
    @Transactional(readOnly = true)
    public SysAccountVo getOne(SysAccountBo bo, Function<LambdaQueryWrapper<SysAccount>, Boolean>
        func) {
        LambdaQueryWrapper<SysAccount> lqw = buildQueryWrapper(bo);
        func.apply(lqw);
        lqw.last("limit 0 offset 1");
            SysAccountVo entity = this.baseMapper.selectVoOne(lqw);
        if (entity == null) {
            return entity;
        }
        return fill(entity);
    }

    /**
    * 查询账号次数
    */
    @Override
    @Transactional(readOnly = true)
    public Long count(QueryWrapper<SysAccount> wrapper) {

        wrapper.last("limit 0 offset 1");
        Long count = this.baseMapper.selectCount(wrapper);
        return count;
    }

    /**
     * 查询账号
     */
    @Override
    @Transactional(readOnly = true)
    public SysAccountVo getOne(QueryWrapper<SysAccount> wrapper) {

        wrapper.last("limit 0 offset 1");
        SysAccountVo entity = this.baseMapper.selectVoOne(wrapper);
        if (entity == null) {
            return entity;
        }
        return fill(entity);
    }
    /**
     * 查询账号
     */
    @Override
    @Transactional(readOnly = true)
    public SysAccountVo getOne(SysAccountBo bo) {

        return getOne(bo, lambdaQueryWrapper -> true);
    }

    /**
     * 查询账号
     */
    @Override
    @Transactional(readOnly = true)
    public SysAccountVo queryById(Long accountId) {
            SysAccountVo entity = baseMapper.selectVoById(accountId);
        if (entity == null) {
            return entity;
        }
        return fill(entity);
    }


        /**
         * 查询账号列表
         */
        @Override
        @Transactional(readOnly = true)
        public TableDataInfo<SysAccountVo> queryPageList(SysAccountBo bo, PageQuery pageQuery) {

            return queryPageList(bo, pageQuery, lambdaQueryWrapper -> true);
        }

        /**
         * 查询账号列表
         */
        @Override
        @Transactional(readOnly = true)
        public TableDataInfo<SysAccountVo> queryPageList(SysAccountBo bo, PageQuery pageQuery,
                                                           Function<LambdaQueryWrapper<SysAccount>, Boolean>
                                                               func) {
            LambdaQueryWrapper<SysAccount> lqw = buildQueryWrapper(bo);
            func.apply(lqw);
            Page<SysAccountVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
            List<SysAccountVo> list = result.getRecords();
            list.forEach(entity -> {
                fill(entity);
            });
            return TableDataInfo.build(result);
        }


    /**
     * 查询账号列表
     */
    @Override
    @Transactional(readOnly = true)
    public List<SysAccountVo> queryList(SysAccountBo bo) {
        return queryList(bo, lambdaQueryWrapper -> true);
    }

    /**
     * 查询账号列表
     */
    @Override
    @Transactional(readOnly = true)
    public List<SysAccountVo> queryList(SysAccountBo bo,
                                          Function<LambdaQueryWrapper<SysAccount>, Boolean>
                                              func) {
        LambdaQueryWrapper<SysAccount> lqw = buildQueryWrapper(bo);
        func.apply(lqw);
        List<SysAccountVo> list = baseMapper.selectVoList(lqw);
        if (list == null) {
            return new ArrayList<SysAccountVo>();
        }
        list.forEach(entity -> {
            fill(entity);
        });
        return list;
    }

    public SysAccountVo fill(SysAccountVo entity) {
        return entity;
    }

    private LambdaQueryWrapper<SysAccount> buildQueryWrapper(SysAccountBo bo) {
        LambdaQueryWrapper<SysAccount> lqw = Wrappers.lambdaQuery();
                    lqw.like(StringUtils.isNotBlank(bo.getName()), SysAccount::getName, bo.getName());
                    lqw.eq(StringUtils.isNotBlank(bo.getCode()), SysAccount::getCode, bo.getCode());
                    lqw.eq(StringUtils.isNotBlank(bo.getStatus()), SysAccount::getStatus, bo.getStatus());
                    lqw.eq(StringUtils.isNotBlank(bo.getToken()), SysAccount::getToken, bo.getToken());
                    lqw.eq(StringUtils.isNotBlank(bo.getType()), SysAccount::getType, bo.getType());
                    lqw.eq(StringUtils.isNotBlank(bo.getWxAppId()), SysAccount::getWxAppId, bo.getWxAppId());
                    lqw.eq(StringUtils.isNotBlank(bo.getWxAppSecret()), SysAccount::getWxAppSecret, bo.getWxAppSecret());
                    lqw.eq(StringUtils.isNotBlank(bo.getAccessToken()), SysAccount::getAccessToken, bo.getAccessToken());
                    lqw.eq(bo.getRefreshTime() != null, SysAccount::getRefreshTime, bo.getRefreshTime());
                    lqw.eq(StringUtils.isNotBlank(bo.getJsApiTicket()), SysAccount::getJsApiTicket, bo.getJsApiTicket());
                    lqw.eq(bo.getJsRefreshTime() != null, SysAccount::getJsRefreshTime, bo.getJsRefreshTime());
                    lqw.eq(StringUtils.isNotBlank(bo.getAesKey()), SysAccount::getAesKey, bo.getAesKey());
                    lqw.eq(StringUtils.isNotBlank(bo.getMerchantCode()), SysAccount::getMerchantCode, bo.getMerchantCode());
                    lqw.eq(StringUtils.isNotBlank(bo.getMerchantKey()), SysAccount::getMerchantKey, bo.getMerchantKey());
                    lqw.eq(StringUtils.isNotBlank(bo.getNotifyUrl()), SysAccount::getNotifyUrl, bo.getNotifyUrl());
                    lqw.eq(StringUtils.isNotBlank(bo.getAppCode()), SysAccount::getAppCode, bo.getAppCode());
        return lqw;
    }

    /**
     * 新增账号
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean insertByBo(SysAccountBo bo) {
        SysAccount add = MapstructUtils.convert(bo, SysAccount. class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setAccountId(add.getAccountId());
        }
        return flag;
    }

    /**
     * 修改账号
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateByBo(SysAccountBo bo) {
        SysAccount update = MapstructUtils.convert(bo, SysAccount. class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(SysAccount entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
    * 删除页面
    */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteWithValidById(Long id, Boolean isValid) {
        return deleteWithValidByIds(CollUtil.newHashSet(id), isValid);
    }

    /**
     * 批量删除账号
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }
}
